package com.ala4.oxcafe.boot.advice;

import com.ala4.oxcafe.common.utils.JSONUtil;
import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 打印返回body的参数
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/6 12:44
 */
@Slf4j
@Component
@ControllerAdvice
public class LogResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@Nullable MethodParameter returnType, @Nullable Class converterType) {
        return true;
    }

    @Override
    @NonNull
    public Object beforeBodyWrite(@Nullable Object body, @Nullable MethodParameter returnType, @Nullable MediaType selectedContentType, @Nullable Class selectedConverterType, @Nullable ServerHttpRequest request, @Nullable ServerHttpResponse response) {
        if (ByteArrayHttpMessageConverter.class.equals(selectedConverterType)) {
            log.info("Result    : 返回byte对象[{}]", request.getURI());
        } else if (body instanceof String strBody) {
            log.info("Result    : {}", strBody);
        } else {
            log.info("Result    : {}", JSONUtil.toJsonStr(body));
        }
        return body;
    }
}
